<?php

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2023/12/8 17:17
 * Desc: 在景点中绑定的与门票关联的分时时段
 */
class Model_Spot_Ticket_Period_Time extends ORM
{

    protected $_table_name = 'spot_ticket_period_time';


    /**
     * 保存时间
     * @param array $period_time_id
     * @param int $spot_id 不传时删除全部关联时段
     * @return void
     */
    public static function del_by_period_time(array $period_time_id, $spot_id = null)
    {
        $builder = DB::delete('spot_ticket_period_time');
        if (!empty($period_time_id)) {
            $builder->where('period_time_id', 'in', $period_time_id);
        }
        if ($spot_id) {
            $builder->where('spot_id', '=', $spot_id);
        }
        $builder->execute();
    }

    /**
     * 保存时段
     * @param int $period_time_id
     * @param int $spot_id
     * @return void
     * @throws Kohana_Exception
     */
    public static function save_period_time($period_time_id, $spot_id)
    {
        $orm = ORM::factory('spot_ticket_period_time')
            ->where('spot_id', '=', $spot_id)
            ->where('period_time_id', '=', $period_time_id)
            ->find();

        if (empty($orm->id)) {
            $orm                 = ORM::factory('spot_ticket_period_time');
            $orm->addtime        = time();
            $orm->period_time_id = $period_time_id;
            $orm->spot_id        = $spot_id;
            $orm->save();
        }
    }

    /**
     * 获取指定景点的分时时段 格式化返回时间 date_str: '12:00-13:00'
     * @param $spot_id
     * @return array
     */
    public static function get_spot_period_time($spot_id)
    {
        $list = DB::select('a.period_time_id', 'b.start', 'b.end')
            ->from(array('spot_ticket_period_time', 'a'))
            ->join(array('spot_period_time', 'b'), 'inner')
            ->on('a.period_time_id', '=', 'b.id')
            ->where('a.spot_id', '=', $spot_id)
            ->execute()
            ->as_array();
        foreach ($list as &$item) {
            $item['date_str'] = $item['start'] . '-' . $item['end'];
        }
        return $list;
    }
}